#pragma once
#include "type_cpp14.h" 
#include "IByteStream.h"
 #include <functional>
#include <string>
namespace  Cc9d {
	using IByteStream = lee8871_byte::IByteStream;

	struct sPkgData {
		uint8 from_port;//源端口号，发送方的端口号；
		uint8 to_port;//目的端口号，接收方的端口号；
		uint16 remote_addr;//远端地址，对于收到的包，是发送方地址，对于要发送的包，是接收方地址；
		uint8 datas[64];//数据部分，最大64字节
	};
	class __EXPORT_DLL Pkg {
	private:
		uint8 type;
		int8 length;//数据长度
	public:			
		sPkgData data;
		uint8 get_from_port() {
			return data.from_port;
		}
		uint8 get_to_port() {
			return data.to_port;
		}
		void asRecvPkg() {
			type = 'r';
		}
		void asSendPkg() {
			type = 's';
		}
		error_code setLen(int len) {
			if(type=='r'){
				return invalid_operation;
			}
			if( (len>64)||(len<0)){
				return argument_error;
			}
			this->length = len;
			return done;
		}
		int getLen(){
			return this->length;
		}

		Pkg() {
			length = -1;
			type = 'n';
		}

		
		std::string toString() {
			std::string rev;
			rev += "length:";
			rev += std::to_string(length);
			rev += " type:";
			rev += std::to_string(type);
			rev += " from_port:";
			rev += std::to_string(data.from_port);
			rev += " to_port:";
			rev += std::to_string(data.to_port);
			rev += " remote_addr:";
			rev += std::to_string(data.remote_addr);
			rev += " datas:";
			for (int i = 0; i < length; i++) {
				rev += std::to_string(data.datas[i]);
				rev += " ";
			}
			return rev;
		}

	};

	class __EXPORT_DLL Transceiver {
	private:
		class Impl;
		std::unique_ptr<Impl> pimpl;
	public:
		Transceiver();
		~Transceiver();
		//绑定一个IByteStream对象，用于发送和接收数据
		error_code band(IByteStream* ch);
		//设置接收回调函数
		error_code setRecvCB(std::function<void(Pkg*)> cb);
		//发送一个包
		error_code sendPkg(Pkg* pkg);
		//执行接收数据，在收到包后调用回调函数。必须轮询调用这个函数。
		//推荐每隔50ms调用一次。
		error_code checkRecv();
	};
}
